package com.assistant.codegen.modules.gen.domain;

import com.assistant.codegen.modules.model.domain.Model;
import com.assistant.codegen.modules.template.domain.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class CodeGenerator {

    public void gen(CodeGenConfigurationProperties configurationProperties, Model model, Template template, boolean overwrite) throws IOException {
        final Context context = new Context(configurationProperties, model);
        final String path = template.getFilePath(context.getValue()) + File.separator + template.getFileName(context.getValue());
        String content = template.getContent(context.getValue());
        createFile(configurationProperties.getBasePath() + File.separator + path, content, overwrite);
    }

    public void createFile(String filePath, String content, boolean overwrite) throws IOException {
        final File file = new File(filePath);
        final File dir = file.getParentFile();
        if (!dir.exists() && !dir.mkdirs()) {
            log.error("创建包目录[{}]失败", dir.getAbsolutePath());
        }
        if (!file.exists() || overwrite) {
            log.info("创建文件[{}]成功", file.getAbsolutePath());
            StreamUtils.copy(content, StandardCharsets.UTF_8, new FileOutputStream(file));
        }
    }

}
